﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebEFDemo
{
    public partial class Update : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UpdateList();
            }
        }

        private void UpdateList()
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);
            if (id == 0)
            {
                Response.Redirect("Index.aspx");
            }
            EFDemoUserListEntities db = new EFDemoUserListEntities();
            var model = db.Student.FirstOrDefault(s => s.stuid == id);
            if (model != null)
            {
                txt_name.Text = model.stuname;
                txt_age.Text =model.stuage.ToString();
                txt_phone.Text = model.phone;
                txt_email.Text = model.email;
                dropclass.SelectedValue =model.classid.ToString();
            }
        }

        protected void btn_update_Click(object sender, EventArgs e)
        {
            //定义id
            int id = Convert.ToInt32(Request.QueryString["id"]);
            //实例化数据库访问上下文
            EFDemoUserListEntities db = new EFDemoUserListEntities();
            //根据id查询实体
            var model = db.Student.FirstOrDefault(s => s.stuid == id);
            if (model != null)
            {
                //修改实体的属性
                model.stuname = txt_name.Text.Trim();
                model.stuage = Convert.ToInt32(txt_age.Text.Trim());
                model.phone = txt_phone.Text.Trim();
                model.email = txt_email.Text.Trim();
                model.classid = Convert.ToInt32(dropclass.SelectedValue);
            }
            //SaveChanges
            if (db.SaveChanges() > 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('修改成功！');location.href='Index.aspx';</script>");
            }
            else
            {
                Response.Write("修改失败！");
            }
        }
    }
}